import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { nanoid } from 'nanoid/non-secure'
import { useUserStore } from './user'
import {
  getFileCategories,
  createFileCategory,
  updateFileCategory,
  deleteFileCategory,
  getFileList,
  uploadFile,
  getFileDetail,
  deleteFile,
  downloadFile,
  getUploadSettings as apiGetUploadSettings,
  updateUploadSettings as apiUpdateUploadSettings
} from '@/utils/fileApi'

export const useFileStorageStore = defineStore(
  'fileStorage',
  () => {
    // 状态
    const categories = ref([])
    const files = ref([])
    const selectedCategory = ref(['all'])
    const searchText = ref('')
    const loading = ref(false)
    const initialized = ref(false)
    const totalFilesCount = ref(0)
    const pagination = ref({
      page: 1,
      limit: 20,
      total: 0,
      totalPages: 0
    })

    // 模态框状态管理
    const isFileModalOpen = ref(false)
    const isCategoryModalOpen = ref(false)

    // 获取用户store
    const userStore = useUserStore()

    // 计算属性
    const filteredFiles = computed(() => {
      let result = files.value

      // 分类过滤
      if (selectedCategory.value[0] !== 'all') {
        result = result.filter((file) => {
          return file.categoryId === selectedCategory.value[0]
        })
      }

      // 搜索过滤
      if (searchText.value) {
        const search = searchText.value.toLowerCase()
        result = result.filter((file) => file.originalName?.toLowerCase().includes(search) || file.description?.toLowerCase().includes(search) || file.uploaderUsername?.toLowerCase().includes(search))
      }

      return result
    })

    // 初始化数据
    const initializeData = async () => {
      loading.value = true
      try {
        // 获取分类列表
        await loadCategories()
        // 获取文件列表
        await loadFiles()
        initialized.value = true
      } catch (error) {
        console.error('初始化文件存储数据失败:', error)
        // 出错时使用默认分类
        categories.value = [
          {
            id: 'all',
            name: '全部',
            description: '所有文件',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ]
      } finally {
        loading.value = false
      }
    }

    // 加载分类列表
    const loadCategories = async () => {
      try {
        const response = await getFileCategories()
        // 更新总文件数量
        totalFilesCount.value = response.data.totalFiles || 0
        // 设置分类列表，包含统计信息
        categories.value = [
          {
            id: 'all',
            name: '全部',
            description: '所有文件',
            file_count: response.data.totalFiles || 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          },
          ...response.data.categories
        ]
      } catch (error) {
        console.error('加载分类失败:', error)
        throw error
      }
    }

    // 加载文件列表
    const loadFiles = async (params = {}) => {
      try {
        const response = await getFileList({
          page: pagination.value.page,
          limit: pagination.value.limit,
          categoryId: selectedCategory.value[0] !== 'all' ? selectedCategory.value[0] : undefined,
          keyword: searchText.value || undefined,
          ...params
        })

        // 转换字段名为驼峰命名法
        files.value = response.data.files.map((file) => ({
          id: file.id,
          filename: file.filename,
          originalName: file.original_name,
          filePath: file.file_path,
          fileSize: file.file_size,
          mimeType: file.mime_type,
          categoryId: file.category_id,
          description: file.description,
          uploaderUsername: file.uploader_username,
          createdAt: file.created_at,
          updatedAt: file.updated_at,
          categoryName: file.category_name
        }))

        pagination.value = response.data.pagination
      } catch (error) {
        console.error('加载文件列表失败:', error)
        throw error
      }
    }

    // 分类管理方法
    const addCategory = async (categoryData) => {
      try {
        const response = await createFileCategory(categoryData)
        const newCategory = response.data

        // 添加到分类列表（除了"全部"分类）
        categories.value.push(newCategory)
        return newCategory
      } catch (error) {
        throw error
      }
    }

    const updateCategory = async (id, categoryData) => {
      try {
        const response = await updateFileCategory(id, categoryData)
        const updatedCategory = response.data

        // 更新分类列表
        const index = categories.value.findIndex((c) => c.id === id)
        if (index !== -1) {
          categories.value[index] = updatedCategory
        }
        return updatedCategory
      } catch (error) {
        throw error
      }
    }

    const deleteCategory = async (id) => {
      try {
        await deleteFileCategory(id)

        // 从分类列表中移除
        const index = categories.value.findIndex((c) => c.id === id)
        if (index !== -1) {
          categories.value.splice(index, 1)
        }

        // 如果当前选中的是被删除的分类，切换到全部分类
        if (selectedCategory.value[0] === id) {
          selectedCategory.value = ['all']
        }
      } catch (error) {
        throw error
      }
    }

    // 文件管理方法
    const uploadFileData = async (formData) => {
      try {
        const response = await uploadFile(formData)
        const uploadedFile = response.data

        // 转换字段名为驼峰命名法
        const newFile = {
          id: uploadedFile.id,
          filename: uploadedFile.filename,
          originalName: uploadedFile.originalName,
          filePath: uploadedFile.path,
          fileSize: uploadedFile.size,
          mimeType: uploadedFile.mimeType,
          categoryId: uploadedFile.categoryId,
          description: uploadedFile.description,
          uploaderUsername: uploadedFile.uploaderUsername,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          categoryName: uploadedFile.categoryName || ''
        }

        // 添加到文件列表
        files.value.unshift(newFile)
        pagination.value.total += 1

        // 重新加载分类数据以更新计数
        await loadCategories()

        return newFile
      } catch (error) {
        throw error
      }
    }

    const updateFile = async (id, data) => {
      try {
        const response = await getFileDetail(id)
        const updatedFile = response.data

        // 更新文件列表
        const index = files.value.findIndex((file) => file.id === id)
        if (index !== -1) {
          files.value[index] = updatedFile
        }
        return updatedFile
      } catch (error) {
        throw error
      }
    }

    const deleteFileData = async (id) => {
      try {
        await deleteFile(id)

        // 从文件列表中移除
        const index = files.value.findIndex((file) => file.id === id)
        if (index !== -1) {
          files.value.splice(index, 1)
          pagination.value.total -= 1
        }

        // 重新加载分类数据以更新计数
        await loadCategories()
      } catch (error) {
        throw error
      }
    }

    // 文件下载
    const downloadFileData = async (file) => {
      try {
        console.log('开始下载文件:', file)
        const response = await downloadFile(file.id)
        console.log('下载响应:', response)

        // 检查响应类型
        const contentType = response.headers.get('content-type')
        console.log('响应类型:', contentType)

        // 对于文件下载，response 直接是 Response 对象
        const blob = await response.blob()
        console.log('Blob 对象:', blob)
        console.log('Blob 大小:', blob.size)
        console.log('Blob 类型:', blob.type)

        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = file.originalName || file.filename
        console.log('下载文件名:', link.download)
        console.log('下载链接:', url)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('下载错误:', error)
        throw error
      }
    }

    // 搜索文件
    const searchFiles = async (keyword) => {
      searchText.value = keyword
      await loadFiles({ keyword })
    }

    // 切换分类
    const selectCategory = async (categoryId) => {
      selectedCategory.value = [categoryId]
      await loadFiles({ categoryId: categoryId !== 'all' ? categoryId : undefined })
    }

    // 分页
    const changePage = async (page) => {
      pagination.value.page = page
      await loadFiles()
    }

    // 获取文件类型图标
    const getFileTypeIcon = (mimeType) => {
      const type = mimeType?.toLowerCase() || ''

      if (type.includes('image')) {
        return 'file-image-outlined'
      } else if (type.includes('video')) {
        return 'video-camera-outlined'
      } else if (type.includes('audio')) {
        return 'audio-outlined'
      } else if (type.includes('pdf')) {
        return 'file-pdf-outlined'
      } else if (type.includes('word') || type.includes('doc')) {
        return 'file-word-outlined'
      } else if (type.includes('excel') || type.includes('xls')) {
        return 'file-excel-outlined'
      } else if (type.includes('powerpoint') || type.includes('ppt')) {
        return 'file-ppt-outlined'
      } else if (type.includes('zip') || type.includes('rar') || type.includes('7z')) {
        return 'file-zip-outlined'
      } else if (type.includes('text') || type.includes('txt')) {
        return 'file-text-outlined'
      } else {
        return 'file-outlined'
      }
    }

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 上传设置管理
    const getUploadSettings = async () => {
      try {
        const response = await apiGetUploadSettings()
        return response.data
      } catch (error) {
        console.error('获取上传设置失败:', error)
        throw error
      }
    }

    const updateUploadSettings = async (settings) => {
      try {
        const response = await apiUpdateUploadSettings(settings)
        return response.data
      } catch (error) {
        console.error('更新上传设置失败:', error)
        throw error
      }
    }

    return {
      // 状态
      categories,
      files,
      selectedCategory,
      searchText,
      loading,
      initialized,
      totalFilesCount,
      pagination,
      isFileModalOpen,
      isCategoryModalOpen,
      // 计算属性
      filteredFiles,
      // 方法
      initializeData,
      loadCategories,
      loadFiles,
      addCategory,
      updateCategory,
      deleteCategory,
      uploadFileData,
      updateFile,
      deleteFileData,
      downloadFileData,
      searchFiles,
      selectCategory,
      changePage,
      getFileTypeIcon,
      formatFileSize,
      formatDate,
      getUploadSettings,
      updateUploadSettings
    }
  },
  {
    persist: {
      // 持久化UI状态
      paths: ['selectedCategory', 'searchText'],
      beforeRestore: (context) => {
        // 这里会在store恢复前调用
      }
    }
  }
)
